<template>
  <el-dialog v-model="visible" width="900px" :append-to-body="true" @close="close" title="成交评估设置">
    <el-button size="small" type="primary" :icon="Plus" style="margin-bottom: 5px" @click="openForm(null)">添加</el-button>
    <el-table :data="tableData" stripe border :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}" :cell-style="{textAlign: 'center'}" v-loading="tableLoading" size="small">
      <el-table-column prop="name" label="名称" width="180"/>
      <el-table-column prop="visible" label="状态" width="150">
        <template #default="{row}">
          <el-switch v-model="row.visible" size="small" @change="visibleChange(row)" :active-value="1" active-text="显示" :inactive-value="0" inactive-text="隐藏"/>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="80"/>
      <el-table-column prop="createTime" label="创建时间" width="140"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column fixed="right" label="操作" width="110">
        <template #default="{row}">
          <el-button size="small" text type="primary" @click="openForm(row)">编辑</el-button>
          <el-button size="small" text type="danger" @click="deleteData(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="page-block">
      <el-pagination
          :small="true"
          style="justify-content: space-between !important;"
          v-model:page-size="params.size"
          v-model:currentPage="params.current"
          v-model:total="total"
          layout="prev, pager, next"
          @size-change="sizeChange"
          @current-change="loadTableData"
      />
    </div>

    <el-dialog v-model="formVisible" width="600px" :append-to-body="true" :title="formData.id ? '编辑' : '添加'">
      <el-form :model="formData" :rules="formRules" size="small" ref="formRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请填写名称" maxlength="32" clearable/>
        </el-form-item>
        <el-form-item label="状态" prop="visible">
          <el-switch v-model="formData.visible" :active-value="1" :inactive-value="0"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="-99999" :max="99999" :controls="false"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button size="small" @click="formVisible = false">关闭</el-button>
        <el-button size="small" type="primary" :loading="submitLoading" @click="saveData(formRef)">提交</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <el-button size="small" type="primary" @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {toRefs, computed, reactive, ref} from 'vue'
import {ElMessageBox, ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import estimateTradeApi from '/@/api/ums/customer/estimateTrade'


export default {
  name: 'Evaluation',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['callback', 'update:dialogVisible'],
  setup(props, context) {
    const {dialogVisible} = toRefs(props)
    const formRef = ref()
    let visible = computed({
      get: () => {
        if (dialogVisible.value) {
          loadTableData()
        }
        return dialogVisible.value
      },
      set: (val) => context.emit('update:dialogVisible', val)
    })
    const state = reactive({
      params: {
        current: 1,
        size: 10
      },
      formData: {
        id: null,
        name: null,
        visible: 1,
        sort: 0,
        remark: null
      },
      formRules: {
        name: {required: true, message: '请填写评估名称', trigger: 'blur'}
      },
      formVisible: false,
      submitLoading: false,
      total: 0,     // 记录条数据
      tableData: [],    // 表格数据
      tableLoading: false   // 表格加载显示控制
    })

    const sizeChange = (size) => {
      state.params.current = 1
      loadTableData()
    }
    const loadTableData = async () => {
      try {
        state.tableLoading = true
        const {data} = await estimateTradeApi.page(state.params)
        if (data) {
          state.total = data.total
          state.tableData = data.records
        }
      } catch (e) {
        console.log('加载表格数据失败\n', e)
      }
      state.tableLoading = false
    }
    const openForm = (trade) => {
      if (trade && trade.id) {
        state.formData = JSON.parse(JSON.stringify(trade))
      } else {
        state.formData = {
          id: null,
          name: null,
          visible: 1,
          sort: 0,
          remark: null
        }
      }
      state.formVisible = true
    }
    const visibleChange = (item) => {
      estimateTradeApi.edit(item).then(res => {
        if (res.data) {
          ElMessage.success('修改成功！')
        }
      }).catch(e => console.log(e))
    }
    // 添加/编辑
    const saveData = (formEl) => {
      formEl.validate(async (valid) => {
        if (!valid) {
          return
        }
        state.submitLoading = true
        let res
        try {
          if (state.formData.id) {
            res = await estimateTradeApi.edit(state.formData)
          } else {
            res = await estimateTradeApi.add(state.formData)
          }
          if (res.data) {
            ElMessage.success('保存成功！')
            state.formVisible = false
            await loadTableData()
          }
        } catch (e) {
          console.log(e)
        }
        state.submitLoading = false
      })
    }
    // 删除标签
    const deleteData = (item) => {
      ElMessageBox.confirm('确定要删除 ' + item.name + ' ？', '警告操作', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        buttonSize: 'small',
        type: 'warning'
      }).then(() => {
        estimateTradeApi.del(item).then(res => {
          if (res.data) {
            loadTableData()
            ElMessage.success('删除成功！')
          }
        }).catch(e => console.log(e))
      }).catch(() => {
      })
    }
    const close = () => context.emit('callback')
    return {
      visible,
      formRef,
      close,
      Plus,
      saveData,
      ...toRefs(state),
      loadTableData,
      deleteData,
      sizeChange,
      openForm,
      visibleChange
    }
  }
}
</script>

<style scoped lang="scss">

</style>
